package com.abcdefg.lotterysystem.service.impl;

import com.abcdefg.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.abcdefg.lotterysystem.common.exception.ServiceException;
import com.abcdefg.lotterysystem.common.utils.CaptchaUtils;
import com.abcdefg.lotterysystem.common.utils.Mail;
import com.abcdefg.lotterysystem.common.utils.RedisUtils;
import com.abcdefg.lotterysystem.common.utils.RegexUtils;
import com.abcdefg.lotterysystem.service.VerificationCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;

    private static final Logger logger = LoggerFactory.getLogger(VerificationCodeServiceImpl.class);
    @Autowired
    private Mail mail;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public void sendVerificationCode(String email) {
        // 校验邮箱格式 xxx@xxx.xxx
        if (!RegexUtils.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        //生成验证码
        String captcha = CaptchaUtils.createCaptcha(6);
        //发送验证码
        try{
            mail.send(email,"验证码！",buildContent(captcha));
        }catch (Exception e){
            logger.error("mail send:",e);
            throw new ServiceException(ServiceErrorCodeConstants.VERIFICATION_CODE_SEND_ERROR);
        }
        //存储到Redis中
        redisUtils.set(VERIFICATION_CODE_PREFIX + email, captcha, VERIFICATION_CODE_TIMEOUT);

    }

    private String buildContent(String captcha) {
        StringBuilder content = new StringBuilder();
        content.append("尊敬的用户,您好! <br/>")
                .append("您的注册验证码如下: </br/>")
                .append("验证码:").append(captcha).append("<br/>")
                .append("感谢您注册我们的抽奖活动! <br/>");
        return content.toString();
    }

    @Override
    public String getVerificationCode(String email) {
        return RegexUtils.checkMail(email) ? redisUtils.get(VERIFICATION_CODE_PREFIX + email) : null;
    }
}
